package cn.zxbetter.secretfile.config;

import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.util.Objects;
import java.util.Properties;

/**
 * 配置文件
 *
 * @author devin
 */
@Getter
@Setter
@ToString
public class SecretConfig {

    /**
     * 密钥
     */
    private String secretKey;

    /**
     * 加密文件的后缀
     */
    private String secretFileSuffix;

    public static SecretConfig from(Properties properties) {
        SecretConfig config = new SecretConfig();
        if (Objects.nonNull(properties)) {
            config.setSecretKey(getConfigValue(properties, "secretKey", true));
            config.setSecretFileSuffix(getConfigValue(properties, "secretFileSuffix", true));
        }
        return config;
    }

    private static String getConfigValue(Properties properties, String key, boolean isRequired) {
        String property = properties.getProperty(key);
        boolean requiredFlag = isRequired && (Objects.isNull(property) || property.length() <= 0);
        if (requiredFlag) {
            throw new RuntimeException("配置项不存在: " + key);
        }

        return property;
    }
}
